﻿using SelfManagement.Common;
using Ninject;
using Ninject.Web.Common;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SelfManagement.Common.Log;
using SelfManagement.Log4Net;
using SelfManagement.Database;
using SelfManagement.Database.EF.MySql;
using SelfManagement.Database.EF;
using log4net;
using SelfManagement.IServices;
using SelfManagement.Services;
using SelfManagement.Account.Manager;

namespace SelfManagement.IOC
{
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private IKernel kernel;

        public NinjectDependencyResolver(IKernel kernelParam)
        {
            kernel = kernelParam;
            AddBindings();
        }

        public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }

        /// <summary>
        /// 注册IOC映射绑定
        /// </summary>
        private void AddBindings()
        {
            #region 绑定工厂对象

            Factory.Container = kernel;
            kernel.Bind<IFactory>().To<Factory>()
                .InSingletonScope();//单例模式
            #endregion 绑定工厂对象

            #region 绑定日志对象

            kernel.Bind<ILogger>().To<Log4NetLogger>()
                .InSingletonScope()//单例模式
                .WithConstructorArgument<ILoggerManager>(new Log4NetLoggerManager())
                .WithConstructorArgument<ILog>(LogManager.GetLogger("common"));//参数

            #endregion 绑定日志对象

            #region 绑定 DBContext

            kernel.Bind(typeof(SelfManagementContext))
                //.To(typeof(SelfManagementSqlServerContext))//使用Sql Server数据库
                .To(typeof(MySqlContext))//使用My Sql数据库
                .InRequestScope();

            #endregion 绑定 DBContext

            #region 绑定 Repository

            kernel.Bind(typeof(IBaseRepository<>)).To(typeof(BaseRepository<>)).InRequestScope();

            #endregion 绑定 Repository

            #region 绑定service

            kernel.Bind(typeof(IBaseService<>)).To(typeof(BaseService<>)).InRequestScope();
            kernel.Bind<IDailyService>().To<DailyService>().InRequestScope();
            kernel.Bind<IArticleCategoryService>().To<ArticleCategoryService>().InRequestScope();
            kernel.Bind<IArticleService>().To<ArticleService>().InRequestScope();
            kernel.Bind<IUserService>().To<UserService>().InRequestScope();
            kernel.Bind<ISeniorService>().To<SeniorService>().InRequestScope();
            #endregion

            #region 绑定 Acount Provider

            kernel.Bind<UserManager>().To<UserManager>().InRequestScope();

            #endregion 绑定 Acount Provider

        }
    }
}